import sys
import os
import copy
import logging

sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), os.path.pardir))

from command_parser.ranlib_parse.ranlib_command_generator import RanlibGenCommand
from command_parser.ranlib_parse.ranlib_command_parser import RanlibParser
from utils.common_utils import *
from configure.compiler_configure import *
from base.context import Context
from utils.db_object_pool import DBObjectPool
from configure.config_logging import capture_log_init


class RanlibHandler(object):
    def __init__(self, command=[]):
        self.command = command
        self.env = {}
        self.cwd = ""
        self.context = Context()
        self.capture_db_handler = None

    def init_env(self):
        self.cwd = os.getcwd()
        self.env = dict(os.environ)
        remove_envs_by_keys(env=self.env, remove_list=["LD_PRELOAD"])
        self.context.update_work_path(os.path.dirname(self.env["IRGEN_WORK_PATH"]))
        self.init_logger()
        self.context.check_redis_cached_config()
        self.capture_db_handler = DBObjectPool.get_db_inst_by_name("ranlib")
    
    def init_logger(self):
        capture_log_init(log_dir=self.context.LOG_DIR, log_mode="a", log_name="ranlib.log", log_level="DEBUG")
    
    def run_ranlib_handler(self):
        parser = RanlibParser(command=self.command, context=self.context)
        ranlib, options = parser.parse_command()
        ranlib = real_binary_path(ranlib)
        
        ret = run_command(command=self.command)
        logging.debug("Record command: {}".format(' '.join(self.command)))
        # print("[INFO] Capture Ranlib Command: %s" % ' '.join(self.command))
        self.record_command(parser=parser)
        return ret
    
    def record_command(self, parser=None):
        
        output_opt = parser.get_output_options()
        output = os.path.abspath(output_opt[0].parameter[0])
        
        input_options = parser.get_input_options()
        input_files = [os.path.abspath(opt.parameter[0]) for opt in input_options]
        
        input_files_md5 = [file_md5(file) for file in input_files]
        command = parser.get_original_command()
        self.save_dep_info(command=command, input_files=input_files, inputs_md5=input_files_md5)
        
        
    def save_dep_info(self, output="", command=[], input_files=[], inputs_md5=[]):
        
        output_files_md5 = [file_md5(file) for file in input_files]
        
        for input_file, pre_md5, out_md5 in zip(input_files, inputs_md5, output_files_md5):
            self.capture_db_handler.set_name_dep(pre_md5, input_file)
            self.capture_db_handler.set_name_dep(out_md5, input_file)
            self.capture_db_handler.set_link_dep(out_md5, pre_md5)
        
        self.capture_db_handler.set_cmd_dep(out_md5, [self.cwd, command])
        
if __name__ == "__main__":
    command = sys.argv[2:]
    handler = RanlibHandler(command=command)
    handler.init_env()
    handler.run_ranlib_handler()
        